package com.qfedu.filter;

import com.qfedu.pojo.AdminPojo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthFilter  implements Filter {
    static String staticres=".jgp.png.gif.css.js.jsp.html.woff.ttf";
    static String commonAuth="/login.to/login.do/welcome.to/index.to";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //静态资源放行
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        String substring = servletPath.substring(servletPath.lastIndexOf("."));
        if (staticres.contains(substring)){
            filterChain.doFilter(request,response);
             return;
        }
        
        
        //公共权限
        String substring1 = servletPath.substring(servletPath.lastIndexOf("/"));
        System.out.println(substring1+"===");
        if (commonAuth.contains(servletPath)){
            filterChain.doFilter(request,response);
            return;
        }
        
        
        //登录判断
        AdminPojo admin = (AdminPojo)request.getSession().getAttribute("admin");
       if (null==admin){
//           request.getRequestDispatcher("login").forward(request,response);
           response.sendRedirect("login.to");
           return;
       }
        
        //根据当前用户判断是否又该权限
        String authsSet = (String)request.getSession().getAttribute("authStr");
          if (authsSet.contains(servletPath)){
              filterChain.doFilter(request,response);
              return;
          }else{
              response.sendRedirect("login.to");
              System.out.println("meiyouquanxian+++++++++++++++++++++");
              return;
          }
    }

    @Override
    public void destroy() {

    }
}
